package com.invengo.module_check.ui.fragment.first_check;

import static com.invengo.module_check.data.entity.BundleKey.KEY_OP_STATE;
import static com.invengo.module_check.data.entity.BundleKey.KEY_SHELFS;

import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.navigation.fragment.NavHostFragment;

import com.invengo.library_db.entity.module_check.ShelfBean;
import com.invengo.module_check.BR;
import com.invengo.module_check.R;
import com.invengo.module_check.data.entity.ActionArgs;
import com.invengo.module_check.data.entity.BundleKey;
import com.invengo.module_check.databinding.FragmentFirstCheckBinding;
import com.invengo.module_check.ui.fragment.first_check.widget.ChangeFirstDialog;

import java.io.Serializable;
import java.util.List;

import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.utils.cache.ACache;
import me.goldze.mvvmhabit.utils.cache.AKey;

public class FirstCheckFragment extends BaseFragment<FragmentFirstCheckBinding, FirstCheckViewModel> {
    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_first_check;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public String getRightTitle() {
        return ACache.getInstance().getAsBoolean(AKey.IS_OFFLINE_MODEL) ? "" : "更新记录";
    }

    @Override
    public void onRightEvent(View view) {
        if (!ACache.getInstance().getAsBoolean(AKey.IS_OFFLINE_MODEL)) {
            viewModel.shelfList.clear();
            NavHostFragment.findNavController(this).navigate(R.id.action_firstCheckFragment_to_firstRecordFragment);
        }
    }

    @Override
    public void initData() {
        viewModel.updateShelfList((List<ShelfBean>) getArguments().getSerializable(KEY_SHELFS),
                getArguments().getString(BundleKey.KEY_START_SHELF_CODE),
                getArguments().getString(BundleKey.KEY_END_SHELF_CODE));
    }

    @Override
    public void initViewObservable() {
        viewModel.ui.changeBookEvent.observe(this, bean -> {
            ChangeFirstDialog.getInstance().showDialog(getActivity(), bean);
        });
        viewModel.ui.tipEvent.observe(this, s -> binding.tip.setText(Html.fromHtml(s)));

        viewModel.ui.nextEvent.observe(this, shelfBeans -> {
            Bundle bundle = new Bundle();
            bundle.putSerializable(KEY_SHELFS, (Serializable) shelfBeans);
            bundle.putSerializable(BundleKey.KEY_ACTION, ActionArgs.ACTION_FIRST_CHECK);
            bundle.putBoolean(KEY_OP_STATE, shelfBeans != null);
            NavHostFragment.findNavController(this).navigate(ActionArgs.ACTION_FIRST_CHECK.getResultAction(), bundle);
        });
    }

}
